const { app, BrowserWindow, Menu, ipcMain, dialog, screen } = require('electron')
const path = require('path')
const fs = require('fs').promises

var baseUrl = 'http://127.0.0.1:9961/'

const defalutWindowSize = '400'
const filePath = './static/storage/window_size.txt'
const mp3FilePath = './static/music/'

// 从文件读取窗口大小信息
async function readWindowSizeFromFile() {
  try {
    const data = await fs.readFile(filePath, 'utf8')
    if (data == '' || data == null) {
      return 400
    }// 这里可能有点缺陷，需要修改一下
    return data
  } catch (err) {
    console.error(`Error reading file at path: ${filePath}`, err)
    throw err
  }
}

// 向文件中写入窗口大小信息
async function writeWindowSizeToFile(size) {
  try {
    await fs.writeFile(filePath, size, 'utf8')
    console.log(`The content has been written to ${filePath}`)
    return true
  } catch (err) {
    console.error(`Error writing to file at path: ${filePath}`, err)
    throw err
  }
}

var win

// 创建窗口
const createWindow = async () => {
  let size = await readWindowSizeFromFile()
  let width = Number(size)
  let height = parseInt(width / 2)
  console.log(parseInt(height))

console.log(screen.getPrimaryDisplay().workAreaSize)

  win = new BrowserWindow({
    width: width,
    height: height,
    center: false,
    x: screen.getPrimaryDisplay().workAreaSize.width - 400, // 设置窗口左上角x坐标为屏幕最右侧减去窗口宽度
    y: 0, // 设置窗口左上角y坐标为0（即屏幕顶部）
    title: '倒计时器',
    resizable: false,
    frame: false,
    transparent: true,
    // alwaysOnTop: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
    }
  })
  // win.setOpacity(0.8)
  win.loadURL(baseUrl)
  // win.loadURL(`file://${path.join(__dirname,"/dist/index.html")}`)
}

// 创建并设置菜单栏
const menu = Menu.buildFromTemplate([])
Menu.setApplicationMenu(menu)

app.whenReady().then(() => {
  createWindow()
})         

let newWin

// 新建一个新的窗口
ipcMain.handle('create-new-window', () => {
  newWin = new BrowserWindow ({
    width: 460,
    height: 470,
    title: '设置',
    resizable: false,
    // alwaysOnTop: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
    }
  })
  // newWin.webContents.openDevTools()
  newWin.loadURL(baseUrl + 'setting.html')
  
  // newWin.loadURL(`file://${path.join(__dirname,"/dist/setting.html")}`)
})

var x
var y

// 关闭新的窗口
ipcMain.handle('close-new-window', async (event, sign) => {
  if (sign === 1) {
    newWin.close()
    return
  }
  const obj = win.getBounds()
  x = obj.x
  y = obj.y
  win.close()
  let size = await readWindowSizeFromFile()
  let width = Number(size)
  console.log(width)
  let height = parseInt(width / 2)
  console.log(parseInt(height))
  win = new BrowserWindow({
    width: width,
    height: height,
    x,
    y,
    title: '倒计时器',
    resizable: false,
    frame: false,
    transparent: true,
    // alwaysOnTop: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
    }
  })
  // win.setOpacity(0.8)
  win.loadURL(baseUrl)
  // win.loadURL(`file://${path.join(__dirname,"/dist/index.html")}`)
  newWin.close()
})

// 关闭主窗口
ipcMain.handle('close-main-window', () => {
  writeWindowSizeToFile(defalutWindowSize)
  win.close()
})

// 最小化主窗口
ipcMain.handle('min-main-window', () => {
  win.minimize()
})

// 设置窗口大小
ipcMain.on('save-window-size', (event, message) => {
  writeWindowSizeToFile(message + '')
})

// 保存mp3到目标路径
const copyMp3ToDestPath = async (sourcePath, fileName) => {
  const destFilePath = mp3FilePath + fileName
  await fs.copyFile(sourcePath, destFilePath)
}

// 获取某一路径下的所有文件的名称
const getFilesNameInDirectory = async () => {
  try {
    const files = await fs.readdir(mp3FilePath)
    return files
  } catch (err) {
    console.error(`读取目录失败: ${err}`);
    return [];
  } 
}

// 获取某一路径下的所有文件的绝对路径
const getFilesResolveInDirectory = async () => {
  try {
    const files = await getFilesNameInDirectory()
    return files.map(file => mp3FilePath + file)
  } catch (err) {
    console.error(`读取目录失败: ${err}`);
    return [];
  }
}

// 打开mp3
ipcMain.handle('upload-mp3', async () => {
  const result = await dialog.showOpenDialog(newWin, {
    properties: ['openFile'], 
    filters: [{ name: 'prompt tone', extensions: ['mp3'] }]
  })

  if (result.canceled) {
    console.log('User canceled the dialog.')
  } else {
    console.log(`Selected file: ${result.filePaths[0]}`)
    // 处理用户选择的文件路径
    let filename = path.basename(result.filePaths[0])
    await copyMp3ToDestPath(result.filePaths[0], filename)
    return true
  }
})

// 获取保存路径下的所有mp3文件名
ipcMain.handle('get-all-mp3-file-name', async () => {
  const filesName = await getFilesNameInDirectory()
  return filesName
})

// 获取保存路径下的所有mp3文件的绝对路径
ipcMain.handle('get-all-mp3-file-resolve', async () => {
  const filesResolve = await getFilesResolveInDirectory()
  return filesResolve
})

// 读取本地路径中的mp3文件并转换为临时URL
ipcMain.handle('read-mp3-file-to-url', async (event, resolveFile) => {
  // console.log(resolve)
  console.log(resolveFile)
  // return new Promise(async (resolve) => {
    const fileData = await fs.readFile(resolveFile)
    const dataUrl = `data:audio/mpeg;base64,${fileData.toString('base64')}`
    // console.log(dataUrl)
    // resolve(dataUrl)
    return dataUrl
  // })
})

// 删除某个路径下的mp3文件
ipcMain.handle('delete-mp3-in-directory', async (event, fileResolve) => {
  try {
    await fs.unlink(fileResolve)
    console.log('Directory and its contents deleted successfully')
    return true
  } catch (error) {
    console.error(`Error deleting directory: ${error}`)
  }
})